﻿using System;
using System.IO;
using System.Xml.Serialization;

namespace MusicPlayer
{
    /// <summary>
    /// xml工具类
    /// </summary>
    public class XmlUtil
    {
        /// <summary>
        /// 将对象序列化为xml字符串
        /// </summary>
        /// <param name="obj">对象</param>
        /// <param name="type"></param>
        /// <returns>xml字符串</returns>
        public static string SerializeObject<T>(T obj)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(T));

            using (StringWriter textWriter = new StringWriter())
            {
                serializer.Serialize(textWriter, obj);
                return textWriter.ToString();
            }
        }

        /// <summary>
        /// 将xml字符串反序列化为制指定对象
        /// </summary>
        /// <typeparam name="T">反序列化目标类型</typeparam>
        /// <param name="xml">xml字符串</param>
        /// <returns>目标类型对象</returns>
        public static T DeserializeObject<T>(string xml)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(T));

            using (StringReader textReader = new StringReader(xml))
            {
                return (T)serializer.Deserialize(textReader);
            }
        }
    }
}
